# ================================================================================
# Copyright (c) 2008, Earlybird Technology Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of Earlybird Technology Inc. nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY Earlybird Technology Inc. ''AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL Earlybird Technology Inc. BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ================================================================================

# Google API's and Extensions
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api import users

# Import Datastore Model
from create_project import Project

# Define Datastore Model
class Punch(db.Model):
    employee = db.UserProperty()
    punch_date = db.DateTimeProperty(auto_now_add=True)
    hours = db.FloatProperty()
    # The value of 'project' is a key
    project = db.ReferenceProperty(Project)
    summary = db.TextProperty()
    

class CreatePunch(webapp.RequestHandler):
    def get(self):
        # Get all the projects that are available
        available_projects = Project.all()
        # Write Header
        self.response.headers['Content-Type']= 'text/html'
        # This HTML form gathers all information needed to create a new punch entity
        self.response.out.write("""
          <html>
            <body>
                <form action="/create_punch" method="post">
                  Project: <br /><select name="project_key">""")
        # Iterate through our list of project names, and display them as options in an HTML pull-down list.
        for project in available_projects:
            self.response.out.write('<option value="' + str(project.key()) + '">' + project.display_name + '</option>')
        self.response.out.write("""
                  </select><br /><br />
                  Hours: <br /><input type="text" name="hours" maxlength="500" /><br /><br />
                  Summary: <br/>
                  (Do not include the following charachters: &amp;  &lt;  &gt;)<br/><textarea name="summary" rows="4" cols="40"></textarea><br /><br /></div>
                  <input type="submit" value="Punch!" />
                </form>
            </body>
          </html>""")

    # This method can not handle bad data well yet. More defensive coding is nessessary.
    # This Post method can be used to create a new punch entity when information is included in the URL.
    def post(self):
        try:
        #todo: remove print statements
            punch_entity = Punch()
            punch_entity.employee = users.get_current_user()
            # If the following assignment raises an exception, all the following code in try block will not be executed.
            punch_entity.hours = float(self.request.get('hours'))
        
            # We need the key as a RefrenceProperty, not as a string
            referenced_project = db.get(self.request.get('project_key'))
            punch_entity.project = referenced_project.key()
            punch_entity.summary = self.request.get('summary')
            punch_entity.put()

            self.redirect("/")
        except ValueError:
#            print 'ValueError exception caught'          # Hour field could not be converted to a float
            self.redirect("/static/error.html")
